package yannuo.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin","*");

        boolean isLogin=false;
        Cookie[] cookieArr = req.getCookies();
        if (cookieArr!=null){
            for (Cookie cookie:cookieArr){
                if (cookie.getName().equals("user")){
                    System.out.println("自动登陆成功");
                    isLogin = true;
                }
            }
        }

        if (!isLogin){
            String userName = req.getParameter("userName");
            String password = req.getParameter("password");
            if (userName.equals("test")&&password.equals("111")){
                System.out.println("登陆成功");

                //创建用户信息Cookie
                Cookie userCookie = new Cookie("user","ok");
                userCookie.setMaxAge(24*60*60);
                resp.addCookie(userCookie);
            }else {
                System.out.println("登陆失败");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
